import axios from 'axios';
import { BaseAIProvider } from './base-provider.js';
import type { AIMessage, AIResponse } from './types.js';

// 智谱AI提供商实现
export class ZhipuAIProvider extends BaseAIProvider {
  constructor() {
    super({
      apiKey: process.env.ZHIPU_API_KEY || '',
      baseURL: 'https://open.bigmodel.cn/api/paas/v4',
      model: process.env.AI_MODEL || 'glm-4-flash',
    });
  }

  getName(): string {
    return '智谱AI';
  }

  isConfigured(): boolean {
    return !!process.env.ZHIPU_API_KEY;
  }

  async callAPI(messages: AIMessage[]): Promise<AIResponse> {
    if (!this.isConfigured()) {
      throw new Error('未配置智谱AI API密钥');
    }

    const requestBody = {
      model: this.config.model,
      messages,
      temperature: 0.8,
      max_tokens: 1000,
    };

    console.log(`[${this.getName()}] 请求参数:`, {
      model: this.config.model,
      messagesCount: messages.length,
      temperature: 0.8,
      max_tokens: 1000,
    });

    try {
      const response = await axios.post(
        `${this.config.baseURL}/chat/completions`,
        requestBody,
        {
          headers: {
            Authorization: `Bearer ${this.config.apiKey}`,
            'Content-Type': 'application/json',
          },
          timeout: 30000,
        }
      );

      console.log(`[${this.getName()}] API调用成功`);
      return response.data;
    } catch (error) {
      console.error(`[${this.getName()}] API调用失败:`, error.response?.data || error.message);
      throw new Error(`智谱AI API调用失败: ${error.response?.data?.error?.message || error.message}`);
    }
  }

  // 智谱AI特有的响应清理方法（如果需要特殊处理）
  cleanResponse(content: string): string {
    // 智谱AI可能有特殊的输出格式，这里可以添加特殊处理
    let cleaned = super.cleanResponse(content);
    
    // 智谱AI特有的清理逻辑（如果有的话）
    // 例如：移除特定的前缀或后缀
    
    return cleaned;
  }
}
